package org.example.journal_items.common;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import java.sql.*;
import java.util.List;

public class JsonListTypeHandler extends BaseTypeHandler<List<String>> {
  private static final ObjectMapper mapper = new ObjectMapper();

  @Override
  public void setNonNullParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType)
      throws SQLException {
    try {
      ps.setString(i, mapper.writeValueAsString(parameter));
    } catch (Exception e) {
      throw new SQLException("Failed to convert list to JSON string", e);
    }
  }

  @Override
  public List<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
    String json = rs.getString(columnName);
    if (json == null)
      return null;
    try {
      return mapper.readValue(json, new TypeReference<List<String>>() {
      });
    } catch (Exception e) {
      throw new SQLException("Failed to parse JSON", e);
    }
  }

  @Override
  public List<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    String json = rs.getString(columnIndex);
    if (json == null)
      return null;
    try {
      return mapper.readValue(json, new TypeReference<List<String>>() {
      });
    } catch (Exception e) {
      throw new SQLException("Failed to parse JSON", e);
    }
  }

  @Override
  public List<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
    String json = cs.getString(columnIndex);
    if (json == null)
      return null;
    try {
      return mapper.readValue(json, new TypeReference<List<String>>() {
      });
    } catch (Exception e) {
      throw new SQLException("Failed to parse JSON", e);
    }
  }
}